﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;
using PlanningGIS.ArcGIS.Custom;
using PlanningGIS.Win.Controls;
using DevComponents.DotNetBar.Controls;
using PlanningGIS.ArcGIS;

namespace PlanningGIS.Engine.Controls
{
    /// <summary>
    /// 数据表关联
    /// </summary>
    public partial class FrmJoins : Office2007Form
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="featlyr">要关联的图层</param>
        public FrmJoins(IFeatureLayer featlyr)
        {
            InitializeComponent();
            _FeatureLayer = featlyr;            
        }

        /// <summary>
        /// 加载窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmJoins_Load(object sender, EventArgs e)
        {
            BoundField((_FeatureLayer.FeatureClass as ITable).Fields, cmbFields);
            if (_HookHelper != null)
            {
                featureLayers = MapHelper.GetAllLayer<IFeatureLayer>(_HookHelper.ActiveView.FocusMap);
                foreach (IFeatureLayer layer in featureLayers)
                {
                    if (layer.Name.Equals(_FeatureLayer.Name,StringComparison.CurrentCultureIgnoreCase))
                        continue;
                    else
                        cmbOtherLayer.Items.Add(layer.Name);
                }
            }
        }

        /// <summary>
        /// 要关联的图层
        /// </summary>
        private IFeatureLayer _FeatureLayer;
       
        /// <summary>
        /// 关联的数据表
        /// </summary>
        private ITable table;

        /// <summary>
        /// 
        /// </summary>
        private List<IFeatureLayer> featureLayers;

        /// <summary>
        /// 
        /// </summary>
        private IHookHelper _HookHelper = null;
        /// <summary>
        /// 获取地图关联对象,通过OnCreate赋值
        /// </summary>
        public object Hook
        {
            set
            {
                _HookHelper = new HookHelper();
                _HookHelper.Hook = value;
            }
        }

        /// <summary>
        /// 打开Table
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOpen_Click(object sender, EventArgs e)
        {
            OpenDataDialog m_OpenDataDialog1 = new OpenDataDialog();
            m_OpenDataDialog1.MultiSelect = false;
            m_OpenDataDialog1.TitleText = "打开Table数据";
            if (m_OpenDataDialog1.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;
            this.Cursor = Cursors.WaitCursor;
            try
            {               
                List<TableNode> pTables = m_OpenDataDialog1.GetTables();
                Application.DoEvents();
                if (pTables == null || pTables.Count == 0) return;
                TableNode tblNode = pTables[0];
                table = (ITable)tblNode.Open();
                if (table != null)
                {
                    cmbOtherLayer.Text = tblNode.Name;
                    BoundField(table.Fields, cmbOtherFields);
                }
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox(this, "加载数据失败：" + ex.Message);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
        
        /// <summary>
        /// 关联数据表更改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmbOtherLayer_SelectedIndexChanged(object sender, EventArgs e)
        {
            int index = cmbOtherLayer.SelectedIndex;
            table = (featureLayers[index] as IAttributeTable).AttributeTable;
            BoundField(table.Fields, cmbOtherFields);
        }
        
        /// <summary>
        /// 绑定字段
        /// </summary>
        /// <param name="fields"></param>
        /// <param name="cmb"></param>
        private void BoundField(IFields fields, ComboBoxEx cmb)
        {
            cmb.Items.Clear();
            cmb.Text = string.Empty;
            if (fields == null) return;
            for (int i = 0; i < fields.FieldCount; i++)
            {
                IField pField = fields.get_Field(i);
                if (pField.Type != esriFieldType.esriFieldTypeGeometry && pField.Type != esriFieldType.esriFieldTypeDate &&
                    pField.Type != esriFieldType.esriFieldTypeBlob && pField.Type != esriFieldType.esriFieldTypeXML)
                {
                    if (string.Format("F{0}", (i + 1).ToString()).Equals(pField.Name) &&
                        pField.Type == esriFieldType.esriFieldTypeString &&
                        pField.Length == 255)
                        break;
                    cmb.Items.Add(pField.Name);
                }
            }
        }

        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFinish_Click(object sender, EventArgs e)
        {
            string mainKey = cmbFields.Text;
            string forgeinKey = cmbOtherFields.Text;
            if (string.IsNullOrEmpty(mainKey) || string.IsNullOrEmpty(forgeinKey))
            {
                MsgHelper.ShowErrorMsgbox(this,"请选择需要关联的字段！");
                return;
            }
            esriJoinType method = rdoAll.Checked ? esriJoinType.esriLeftOuterJoin : esriJoinType.esriLeftInnerJoin;
            //开始关联操作
            try
            {
                IMemoryRelationshipClassFactory pMemRelCFac = new MemoryRelationshipClassFactoryClass();
                IRelationshipClass pRelClass = pMemRelCFac.Open("TableToLayer",
                    _FeatureLayer.FeatureClass as IObjectClass, mainKey, table as IObjectClass, forgeinKey,
                    "forward", "backward", esriRelCardinality.esriRelCardinalityOneToOne);
                IDisplayRelationshipClass pDispRelClass = _FeatureLayer as IDisplayRelationshipClass;
                pDispRelClass.DisplayRelationshipClass(pRelClass, method);
                //结束关联操作
                this.Close();
            }
            catch(Exception ex)
            {
                MsgHelper.ShowErrorMsgbox(this, "关联错误：" + ex.Message);
            }
            
        }

    }
}
